#include "KDTree.h"


//debug information
#include "Util.h"
#ifdef _DEBUG
   #define new MYDEBUG_NEW
#endif



namespace kdtree
{

KDTree::KDTree(void)
{
	root = 0; 
	totalNodes = 0; 
	splitCriterion = SPLIT_USE_MAX_ALLOWED_ERROR ; 
	generalizerType = GENERALIZER_USE_MEAN; 
	eta = 1; 
}

void KDTree::setSplitCriterion(int v)
{
	if (v == SPLIT_USE_MAX_SAMPLES )
		splitCriterion = SPLIT_USE_MAX_SAMPLES ; 
	else
		splitCriterion = SPLIT_USE_MAX_ALLOWED_ERROR ; 
}

KDTree::~KDTree(void)
{
	resetPoints(); 
}


double KDTree::getConfidence(const Observation st)
{
	if (!root)
		return 0; 

	return root->getPublicKnownness(st); 
}


void KDTree::print()
{
	


}
void KDTree::setDimensionParameters(int dim, double_range_t* r)
{
	dimension = dim; 
	ranges = r; 

	if (! KRect::widths)
		KRect::widths = new double[dimension];	//warning: who deletes this?
	for(int i=0; i< dimension ; i++)
	{
		KRect::widths[i] = ranges[i].max - ranges[i].min;  
	}
}

bool KDTree::predict(const Observation o, double& result)
{
	if (!root)
		return false; 

	return root->predict(o, result); 

}


void KDTree::resetPoints()
{

#ifdef DEBUG_PRINT
	printf("-------------------begin destroying kdtree \n"); 
#endif

	if(root)
		delete root; 

	if (root)
	{
		root = 0; 
	}

	totalNodes = 0; 
}

//public methods
void KDTree::addPoint(Observation pt, double target)
{

#ifdef DEBUG_PRINT
	printf("adding one point to tree\n" ); 
#endif
	if (!root)
	{
		KRect* rect = new KRect(dimension, ranges); 
		root = new KNode(this, 0, rect); 
	}
	
	std::pair<Observation,double> param(pt, target); 
	root->addPoint(param); 
}


void KDTree::addPoints(list<KData>& l)
{
	if (!root)
	{
		KRect* rect = new KRect(dimension,ranges); 
		root = new KNode(this, 0, rect); 
	}
	
	root->addPoints(l ); 
}

void KDTree::addPoints(list<Transition>& history, int actionIndex, int targetDim)
{
	//warning: not implemented yet!
	printf("WARNING: KDTree::addPoints for batch learning is called but not implemented yet\n"); 

}

}//namespace

